<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="入库时间" prop="dateInfo" clearable>
        <el-date-picker clearable v-model="queryParams.dateInfo" type="date" value-format="yyyy-MM-dd"
          placeholder="请选择日期">
        </el-date-picker>
      </el-form-item>

      <!-- <el-form-item label="是否分配" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择客户是否分配" clearable>
          <el-option label="未分配" value="0"></el-option>
          <el-option label="已分配" value="1"></el-option>
        </el-select>
      </el-form-item> -->

      <!-- <el-form-item label="客户星级" prop="starNumber">
        <el-select v-model="queryParams.starNumber" placeholder="请选择客户星级" clearable>
          <el-option v-for="(item, i) in extData.StartType || []" :key="i" :label="item.name"
            :value="item.value"></el-option>
        </el-select>
      </el-form-item> -->
      <!-- <el-form-item label="状态" prop="stateInfo">
        <el-select v-model="queryParams.stateInfo" placeholder="请选择跟进情况" clearable>
          <el-option v-for="(item, i) in extData.DataStatus || []" :key="i" :label="item.name"
            :value="item.value"></el-option>
        </el-select>
      </el-form-item> -->

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="small" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="small" @click="resetQuery">重置</el-button>
      </el-form-item>

    </el-form>


    <el-row :gutter="10" class="mb8">
      <!-- <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="small" @click="handleAdd"
          v-hasPermi="['merchantdata:poolInfo:batchFenpei']">批量分配</el-button>
      </el-col> -->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="poolInfoList">
      <!-- <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" align="center" prop="id" /> -->
      <el-table-column label="入库时间" align="center">
        <template slot-scope="scope">
          {{ formatTimestamp(scope.row.createTime) }}
        </template>
      </el-table-column>

      <el-table-column label="个人信息" align="center" width="200">
        <template slot-scope="scope">
          {{ scope.row.realname }} -- {{ scope.row.sex === 1 ? '男' : '女' }} -- {{ scope.row.age }}
        </template>
      </el-table-column>
      <el-table-column label="所属地" align="center">
        <template slot-scope="scope">
          {{ scope.row.province }} -- {{ scope.row.city }}
        </template>
      </el-table-column>

      <el-table-column label="分配成员" align="center" prop="nickName">
        <template slot-scope="scope">
          {{ scope.row.status === 0 ? '' : scope.row.nickName }}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">

          <el-button size="small" type="text" v-hasPermi="['merchantdata:date:fenpei']"
            @click="handleAssign(scope.row)" :disabled="scope.row.distStatus !== 0">分配</el-button>

          <el-button size="small" type="text" v-hasPermi="['merchant:pushInfo:laoqu']"
            @click="handleUpdate(scope.row)" :disabled="scope.row.distStatus !== 0">捞取</el-button>
        </template>
      </el-table-column>


    </el-table>



    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 分配用户弹窗 -->
    <el-dialog :title="title" :visible.sync="fenpeidialogVisible" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="员工姓名">
          <el-select v-model="form.selectedUserId" placeholder="请选择用户">
            <el-option v-for="user in userList" :key="user.uid" :label="user.nickName" :value="user.uid"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleSubmit">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 捞取用户弹窗 -->
    <el-dialog :title="title" :visible.sync="dialogVisible" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <p style="text-align: center;">确认要捞取该用户？</p>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>
<script>





import { listPoolInfo,laoquPoolInfo } from "@/api/merchant/pushInfo";
import { baseInfoData } from "@/api/merchantdata/allocateInfo";
import { listAllUserInfo } from "@/api/merchantdata/userInfo";
import { Notification } from 'element-ui';
import { isHavePermission } from '@/directive/permission/hasPermi';
export default {
  name: "PoolInfo",
  data() {
    return {
      extData: {},
      detailsDialogVisible: false, // 弹窗可见状态
      selectedRow: null,
      rules: {
        remarkInfo: [
          { required: true, message: "请输入客户跟踪", trigger: "blur" }
        ],
        starNumber: [
          { required: true, message: "请输入客户星级", trigger: "blur" }
        ]
      },
      dialogVisible: false,
      fenpeidialogVisible: false,
      dialogTitle: "",
      updateType: "",
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      userList: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 商户客户公海信息表格数据
      poolInfoList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      notification: {  // 通知属性
        title: '',
        message: '',
        type: 'success',
        duration: 5000,
      },
      // 查询参数
      queryParams: {
        dateInfo: null,
        pageNum: 1,
        pageSize: 10,
        dateInfo: null,
        starNumber: null,
        status: null
      },
      // 表单参数
      form: {
        status: null,
        userId: null,
      },
    };
  },
  created() {
    this.getList();
    this.getOptions();
    this.fetchUserList();
 
    const thirtySeconds = 30 * 1000; 
    setInterval(() => {
      this.getList();
    }, thirtySeconds);
  },

  methods: {
    isHavePermission,
    getOptions() {
      baseInfoData().then((response) => {
        this.extData = response.data;
      });
    },
    /**转换入库时间格式 */
    formatTimestamp(timestamp) {
      if (!timestamp) {
        return '';
      }
      const date = new Date(timestamp);
      const formattedDate = `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
      return formattedDate;
    },

    // 用户详情弹窗
    async handleDetailsDialog(row) {
      this.$refs.MemberRef.show(row.uid)
    },

    closeDetailsDialog() {
      this.selectedRow = null; // 重置selectedRow
      this.detailsDialogVisible = false;
    },

    handleSubmit() {
      console.log(this.form.selectedUserId);

      // 检查是否选择了员工姓名
      if (!this.form.selectedUserId) {
        this.$message.error("请选择员工姓名");
        return;
      }

      // 检查下拉框是否有值
      if (this.userList.length === 0) {
        this.$message.error("请先添加员工再进行分配");
        return;
      }
      // 执行提交逻辑
      this.submit();
    },

    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },

    // 显示通知的函数
    showNotification(title, message, type = 'success', duration = 15000) {
      this.notification.title = title;
      this.notification.message = message;
      this.notification.type = type;
      this.notification.duration = duration;
      Notification(this.notification);
    },

    /** 查询商户客户公海信息列表 */
    getList() {
      const oldTotal = this.total;
      listPoolInfo(this.queryParams).then(response => {
        this.poolInfoList = response.rows;
        this.total = response.total;
        this.loading = false;
        if (this.total > oldTotal) {
          if(oldTotal!=0){
            this.showNotification('通知', '您有新的客户入库，请及时联系');
          }
        }
      });
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
      this.dialogVisible = false;
      this.fenpeidialogVisible = false;
    },
    // 表单重置
    reset() {
      this.form = {
        createTime: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },

    fetchUserList() {
      listAllUserInfo()
        .then(response => {
          this.userList = response.rows; // 将获取到的用户列表数据赋值给userList
        })
        .catch(error => {
          console.error("获取用户列表失败:", error);
        });
    },

    /**分配 */
    handleAssign(row) {
      this.reset();
      this.form.id = row.id;
      this.form.status = 1;
      this.fenpeidialogVisible = true;
    },

    /**捞取 */
    handleUpdate(row) {
      this.reset();
      this.form.id = row.id;
      this.form.uid = row.uid;
      this.form.infoId = row.infoId;
      this.form.dateInfo = row.dateInfo;
      this.form.deptId = row.deptId;
      this.dialogVisible = true;
    },

    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            laoquPoolInfo(this.form).then(response => {
              this.$modal.msgSuccess("捞取成功");
              this.dialogVisible = false;
              this.getList();
            });
          }
        }
      });
    },
    submit() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            const requestData = {
              id: this.form.id,
              status: this.form.status,
              userId: this.form.selectedUserId
            };
            fenpeiPoolInfo(requestData).then(response => {
              this.$modal.msgSuccess("分配成功");
              this.fenpeidialogVisible = false;
              this.getList();
            });
          }
        }
      });
    },
  }
};
</script>
